
local file = io.open(arg[1],"rb");
assert(file,"open file error:"..arg[1]);
local offset = tonumber(arg[2]) or 0;
local data = file:read('*a');
local len = (tonumber(arg[3]) and tonumber(arg[3]) + offset) or #data;
if(len>#data)then len = #data; end
local sdata_len = WIDTH/8;
offset = offset + 1;

WIDTH = WIDTH or (1*8);
DEPTH = DEPTH or math.floor((len-offset+1)/sdata_len);
local out = io.stdout;
local err = io.stderr;
err:write(string.format('offset:%d,%d\n',offset-1,len));

local info = [[
#File_format=Hex
#Address_depth=#LEN#
#Data_width=#WIDTH#
]]

info = info:gsub('#LEN#',string.format('%d',DEPTH));
info = info:gsub('#WIDTH#',WIDTH);
out:write(info);

for k=offset,DEPTH*sdata_len,sdata_len do
    local byte = string.byte(data,k);
    local fmt =  string.format('%%0%dX',sdata_len*2);
    if(sdata_len>=2 and byte~=nil)then
        byte = byte + string.byte(data,k+1)*0x100;
        fmt = '%04X';
    end
    if(sdata_len==4 and byte~=nil)then
        fmt = '%08X';
        byte = byte + string.byte(data,k+2)*0x10000;
        byte = byte + string.byte(data,k+3)*0x1000000;
    end
    byte = byte or 0;

    local hex = string.format(fmt,byte);
    local idx = k - offset;
    local str = string.format('%s\n',hex);
    out:write(str);
    -- if((k-offset+1)%0x10==0)then
    --     --换行
    --     out:write('\n');
    -- end
end


